package bean;

import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.Name;
import entity.Contact;
import entity.RegisteredUser;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.persistence.PostLoad;
import manager.ContactManager;

@ManagedBean
@RequestScoped
public class FacebookImportBean implements Serializable{


	@ManagedProperty(value="#{registeredUserBean.registeredUser}")
	protected RegisteredUser registeredUser;

	@ManagedProperty(value="#{facebook_contacts}")
	protected List<Contact> facebookContacts;

	public void setSaveContact(Contact newContact){
        ContactManager cm = new ContactManager();
        try {
			newContact.setRegisteredUser(registeredUser);
            RegisteredUser reguser = newContact.getRegisteredUser();

            System.out.println("REgistered user: " + reguser.getId());
            System.out.println("new contact info" + newContact.getEmail() + newContact.getLastName() + newContact.getFirstName());
            if (newContact.getEmail().matches("[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}") && cm.contactExists(reguser, newContact.getEmail()) == false) {
				for(int i=0;i<facebookContacts.size();i++){
					if(facebookContacts.get(i)==newContact){
						System.out.println("found at "+i);
						facebookContacts.remove(i);
						break;
					}
				}

                cm.create(newContact);
                reguser.getContacts().add(newContact);
                //rum.edit(newContact.getRegisteredUser());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

	}

	public List<Contact> getFacebookContacts() {
		return facebookContacts;
	}

	public void setFacebookContacts(List<Contact> facebookContacts) {
		this.facebookContacts = facebookContacts;
	}

	public RegisteredUser getRegisteredUser() {
		return registeredUser;
	}

	public void setRegisteredUser(RegisteredUser registeredUser) {
		this.registeredUser = registeredUser;
	}

}
